<template>
  <el-input placeholder="请输入手机尾号" v-model="search" style="width: 300px;"></el-input>
  <el-button type="primary" @click="getOrderList">查询</el-button>
  <el-table
      :data="page"
      style="width: 100%">
    <el-table-column
        prop="id"
        label="订单编号"
        width="240">
    </el-table-column>
    <el-table-column
        prop="user_name"
        label="用户名"
        width="180">
    </el-table-column>
    <el-table-column
        prop="user_phone"
        label="电话">
    </el-table-column>
    <el-table-column
        prop="pickupName"
        label="自提点">
    </el-table-column>
    <el-table-column
        prop="total_amount"
        label="订单金额">
    </el-table-column>
    <el-table-column
        label="退款状态"
        width="100"
        align="center">
      <template #default="scope">
        <span v-if="scope.row.hasRefundPending" style="color: red;">有待退款</span>
        <span v-else>正常</span>
      </template>
    </el-table-column>
    <el-table-column
        header-align="center"
        align="center"
        label="操作">
      <template #default="scope">
        <div style="display: flex; justify-content: center; gap: 8px;">
          <el-button
            v-if="scope.row.canShip"
            type="primary"
            @click="updateStatus(scope.row.id)">
            发货
          </el-button>
          <el-button type="primary" @click="OrderInfo(scope.row.id)">查看</el-button>
          <el-button
            v-if="scope.row.hasRefundPending"
            type="warning"
            @click="OrderInfo(scope.row.id)">
            处理退款
          </el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="orderDetailVisible" title="订单详情" width="700px">
    <el-table :data="orderDetails" border>
<!--      <el-table-column prop="id" label="小订单编号" width="200"/>-->
      <el-table-column prop="productName" label="商品名称" width="200"/>
      <el-table-column prop="quantity" label="数量" width="80" align="center"/>
      <el-table-column prop="price" label="单价" width="80" align="center"/>
      <el-table-column prop="status" label="小订单状态" width="100" align="center"/>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === '待退款'"
            type="warning"
            @click="showRefundDetail(scope.row.id)">
            查看退款
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <el-dialog v-model="refundDetailVisible" title="退款详情" width="500px" append-to-body>
    <div>退款原因：{{ refundDetail.reason }}</div>
    <div>退款详细原因：{{ refundDetail.reason_detail }}</div>
    <div v-if="refundDetail.image">
      <div>用户上传图片：</div>
      <el-image
        :src="'http://192.168.90.26:8080/' + refundDetail.image"
        style="width: 100px; margin-right: 10px"
      />
    </div>
    <div style="margin-top: 20px; text-align: right;">
      <el-button type="success" @click="agreeRefund">同意退款</el-button>
      <el-button type="danger" @click="cancelRefund">取消退款</el-button>
    </div>
  </el-dialog>

</template>

<script setup>
import {onMounted, ref, reactive} from "vue";
import axios from "axios";
import {ElTable, ElTableColumn, ElButton, ElInput, ElMessage} from "element-plus";
let search = ''
let page = ref([])
const orderDetailVisible = ref(false)
const orderDetails = ref([])
const productMap = ref({})
const refundDetailVisible = ref(false)
const refundDetail = ref({
  reason: '',
  reason_detail: '',
  image: '',
  orderId: null
})
onMounted(()=>{
  getOrderList()
})
async function getOrderList() {
  const res = await axios.get('http://192.168.90.26:8080/order/findAll?phone=' + search)
  const orders = res.data

  // 并发获取每个大订单下的小订单
  const allSubOrders = await Promise.all(
    orders.map(order =>
      axios.get('http://192.168.90.26:8080/order/findAllById?id=' + order.id)
        .then(res => res.data)
        .catch(() => [])
    )
  )

  // 给每个大订单加上hasRefundPending和canShip字段
  orders.forEach((order, idx) => {
    const subOrders = allSubOrders[idx]
    order.hasRefundPending = hasRefundPending(subOrders)
    order.canShip = canShip(subOrders)
  })

  page.value = orders
}

// 判断是否有待退款小订单
function hasRefundPending(subOrders) {
  return subOrders.some(item => item.status === '待退款')
}

// 判断是否所有小订单都为已支付
function canShip(subOrders) {
  return subOrders.length > 0 && subOrders.every(item => item.status === '已支付')
}
const updateStatus = (id) => {
  if (!id){
    ElMessage.warning('请选择要发货的项');
    return;
  }
  if (!confirm('确定要发货吗？')){
    return;
  }
  axios.get('http://192.168.90.26:8080/order/updatestatus?id='+id).then(res=>{
    if (res.data) {
      ElMessage.success('发货成功');
      axios.get('http://192.168.90.26:8080/order/findAllById?id='+id).then(res=>{
        const orderItems = res.data
        orderItems.forEach(item => {
          axios.post('/log/add', {
            product_id: item.product_id,
            change_quantity: -item.quantity,
            change_reason: '销售出库',
            change_time: new Date()
          })
        })
        getOrderList()
      })
    } else {
      ElMessage.error('发货失败');
    }
  })
}
const fetchProductNames = async (productIds) => {
  try {
    const res = await axios.get('http://192.168.90.26:8080/product/list', {
      params: { ids: productIds.join(',') }
    })
    res.data.forEach(product => {
      productMap.value[product.id] = product.name
    })
  } catch (error) {
    console.error('获取商品名称失败:', error)
  }
}

const OrderInfo = async (id) => {
  try {
    const res = await axios.get('http://192.168.90.26:8080/order/findAllById?id='+id)
    const orderItems = res.data
    console.log(orderItems)
    const productIds = orderItems.map(item => item.product_id)
    await fetchProductNames(productIds)
    
    orderDetails.value = orderItems.map(item => ({
      productName: productMap.value[item.product_id] || '未知商品',
      id: item.id,
      quantity: item.quantity,
      price: item.price,
      status: item.status
    }))
    orderDetailVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}
const showRefundDetail = async (id) => {
  try {
    const res = await axios.get(`http://192.168.90.26:8080/order_detail/refund?order_id=`+id)
    refundDetail.value = {
      ...res.data,
      orderId: id
    }
    refundDetailVisible.value = true
  } catch (e) {
    ElMessage.error('获取退款详情失败')
  }
}
const agreeRefund = async () => {
  await axios.get('http://192.168.90.26:8080/order_detail/agreerefund?id='+refundDetail.value.orderId)
  refundDetailVisible.value = false
  getOrderList()
  ElMessage.success('已同意退款')
}


const cancelRefund = async () => {
  await axios.get('http://192.168.90.26:8080/order_detail/refuserefund?id='+refundDetail.value.orderId)
  refundDetailVisible.value = false
  getOrderList()
  ElMessage.success('已取消退款')
}
</script>

<style scoped>

</style>